package com.googlecode.jvmpart.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Properties;

public class URLUtils {
	private static final String KEY_PROXY_HOST = "proxyHost";
	private static final String KEY_PROXY_PORT = "proxyPort";

	static {
		String proxyHost = System.getProperty(KEY_PROXY_HOST);
		if (proxyHost != null) {
			Properties prop = System.getProperties();
			prop.put(   "proxySet",   "true"   );     
			prop.put(KEY_PROXY_HOST, proxyHost);
			prop.put(KEY_PROXY_PORT, System.getProperty(KEY_PROXY_PORT));
		}
	}

	public static String retrieve(String url) throws IOException {
		return retrieve(new URL(url));
	}
	public static String retrieve(String url, String charset) throws IOException {
		return retrieve(new URL(url), charset);		
	}
	public static String retrieve(URL url) throws IOException {
		return retrieve(url, "UTF-8");
	}

	public static String retrieve(URL url, String charset) throws IOException {
		BufferedReader in = null;
		try {
			URLConnection conn = url.openConnection();
			conn.setRequestProperty("User-Agent",
					"Mozilla/4.0 (compatible; MSIE 8.0)");
			conn.setRequestProperty("Cache-Control", "no-cache");
			conn.setRequestProperty("Pragma:", "no-cache");
			in = new BufferedReader(
					new InputStreamReader(conn.getInputStream(), charset));
			StringBuffer buf = new StringBuffer(1024 * 5);
			String line = null;
			while ((line = in.readLine()) != null) {
				buf.append(line);
			}
			return buf.toString();
		} catch (IOException e) {
			throw e;
		} finally {
			try {
				if (in != null)
					in.close();
			} catch (Exception e) {
			}
		}
	}

	public static void simpleDownload(URL url, File dest) throws IOException {
		simpleDownload(url, dest, true);
	}

	public static void simpleDownload(URL url, File dest, boolean skipIfExist)
			throws IOException {
		InputStream in = null;
		OutputStream out = null;
		File dir = null;
		try {
			if (!dest.exists()) {
				dest.mkdirs();
				dir = dest;
			} else {
				if (dest.isFile())
					dir = dest.getParentFile();
				else
					dir = dest;
			}
			String filename = url.getFile();
			filename = filename.substring(filename.lastIndexOf('/') + 1);
			if (skipIfExist && new File(dir, filename).exists())
				return;
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(15000);
			conn.setRequestProperty("User-Agent",
					"Mozilla/4.0 (compatible; MSIE 8.0)");
			conn.setRequestProperty("Cache-Control", "no-cache");
			conn.setRequestProperty("Pragma:", "no-cache");
			String suffix = null;
			if (filename.indexOf('?') != -1) {
				filename = filename.substring(0, filename.lastIndexOf('?'));
				suffix = conn.getContentType();
				if (suffix != null) {
					int ind = suffix.indexOf('/') + 1;
					suffix = suffix.substring(ind, ind + 3);
					filename += "." + suffix;
				}
			}
			in = conn.getInputStream();
			byte[] buf = new byte[1024 * 5];
			int read = 0;
			File file = new File(dir, filename);
			if (skipIfExist && file.exists())
				return;
			int index = 0;
			while (file.exists()) {
				int pos = filename.lastIndexOf('.');
				if (pos != -1) {
					suffix = filename.substring(pos);
					filename = filename.substring(0, pos);
				} else
					suffix = "";
				file = new File(dir, filename + "_" + index + suffix);
				index++;
			}
			System.out.println(file.getAbsolutePath());
			file.createNewFile();
			out = new FileOutputStream(file);
			while ((read = in.read(buf)) != -1) {
				out.write(buf, 0, read);
			}
		} catch (IOException e) {
			throw e;
		} finally {
			try {
				if (out != null)
					out.close();
				if (in != null)
					in.close();
			} catch (Exception e) {
			}
		}

	}
}
